<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Profile extends MY_Controller {

    private $_user_id = 0;
    
    public function __construct() {
        parent:: __construct();
        if(!$this->logged_in()) {
            $this->session->set_userdata("redirect", base_url("profile"));
            redirect("login");
        }
        $infoUser = $this->logged_in();
        if(!empty($infoUser)) {
            $this->_user_id = $infoUser['id'];
        }
        $this->load->helper("url");
        $this->load->model("member_model");
        $this->load->library("form_validation");
    }

    //create a new user
    function index() {
        //load the registration helper under helper folder
        $this->load->helper('registration');

        $this->data['title'] = "Register User";

        // validate form input  
        $this->form_validation->set_rules('fullname', 'Họ và Tên', 'required|xss_clean');
        $this->form_validation->set_rules('birth_date_year', 'Năm', 'xss_clean');
        $this->form_validation->set_rules('birth_date__nc_month', 'Tháng', 'xss_clean');
        $this->form_validation->set_rules('birth_date__nc_day', 'Ngày', 'xss_clean');
        $this->form_validation->set_rules('address', 'Địa chỉ', 'required|xss_clean');
        $this->form_validation->set_rules('city', 'Tỉnh/Thành phố', 'required|xss_clean');
        $this->form_validation->set_rules('state', 'Quận/Huyện', 'required|xss_clean');
        $this->form_validation->set_rules('ward', 'Phường/Xã', 'required|xss_clean');
        $this->form_validation->set_rules('phone', 'Điện thoại', 'required|xss_clean');
        $this->form_validation->set_rules('email', 'Địa chỉ email', 'required|valid_email');
        
        $infoUser = $this->member_model->get_member($this->_user_id);
        $data = $this->_getData($infoUser, $_POST);
        
        if ($this->form_validation->run() == true) {
            $this->member_model->save($data, $this->_user_id);
            $this->data['message'] = "Thông tin của bạn đã được lưu lại";
        } else {
            //display the create user form
            //set the flash data error message if there is one
            $this->data['message'] = (validation_errors() ? validation_errors() : ($this->session->flashdata('message')));

            $this->data['fullname'] = array(
                'name' => 'fullname',
                'id' => 'fullname',
                'type' => 'text',
                'size' => 32,
                'maxlength' => 32,
                'value' => $data['lb_full_name'],
            );

            $year = $this->input->post('birth_date_year');
            $this->data['birth_date_year'] = buildYearDropdown('birth_date_year', !empty($year)?$year:date_format(new DateTime($data['lb_birthday']), "Y"));

            $month = $this->input->post('birth_date_month');
            $this->data['birth_date_month'] = buildMonthDropdown('birth_date_month', !empty($month)?$month:date_format(new DateTime($data['lb_birthday']), "m"));

            $day = $this->input->post('birth_date_day');
            $this->data['birth_date_day'] = buildDayDropdown('birth_date_day',  !empty($day)?$day:date_format(new DateTime($data['lb_birthday']), "d"));

            $this->data['address'] = array(
                'name' => 'address',
                'id' => 'address',
                'type' => 'text',
                'size' => 32,
                'maxlength' => 64,
                'value' => $data['lb_address'],
            );

            $this->data['city'] = buildCityDropdown('city', $data['lb_city']);
            
            $this->data['state'] = buildStateDropdown('state', $data['lb_state'], $data['lb_city']);
            
            $this->data['ward'] = buildWardDropdown('ward', $data['lb_ward'], $data['lb_state']);
            
            $this->data['phone'] = array(
                'name' => 'phone',
                'id' => 'phone',
                'type' => 'text',
                'size' => 32,
                'maxlength' => 32,
                'value' => $data['lb_phone'],
            );
            
            $this->data['email'] = array(
                'name' => 'email',
                'id' => 'email',
                'type' => 'text',
                'size' => 32,
                'maxlength' => 128,
                'value' => $data['lb_email'],
            );
            
            $this->data['password'] = array(
                'name' => 'password',
                'id' => 'password',
                'type' => 'password',
                'size' => 32,
                'maxlength' => 32,
                'value' => $this->form_validation->set_value('password'),
            );
            
            $this->data['password_confirm'] = array(
                'name' => 'password_confirm',
                'id' => 'password_confirm',
                'type' => 'password',
                'size' => 32,
                'maxlength' => 32,
                'value' => $this->form_validation->set_value('password_confirm'),
            );
            
            $this->_templates['page'] = 'profile/index';
            $this->site_lib->load($this->_templates['page'], $this->data);
        }
    }
    
    public function update() {
        //load the registration helper under helper folder
        $this->load->helper('registration');

        $this->data['title'] = "Register User";

        // validate form input  
        $this->form_validation->set_rules('fullname', 'Họ và Tên', 'required|xss_clean');
        $this->form_validation->set_rules('birth_date_year', 'Năm', 'xss_clean');
        $this->form_validation->set_rules('birth_date__nc_month', 'Tháng', 'xss_clean');
        $this->form_validation->set_rules('birth_date__nc_day', 'Ngày', 'xss_clean');
        $this->form_validation->set_rules('address', 'Địa chỉ', 'required|xss_clean');
        $this->form_validation->set_rules('city', 'Tỉnh/Thành phố', 'required|xss_clean');
        $this->form_validation->set_rules('state', 'Quận/Huyện', 'xss_clean');
        $this->form_validation->set_rules('phone', 'Điện thoại', 'required|xss_clean');
        $this->form_validation->set_rules('email', 'Địa chỉ email', 'required|valid_email');
        
        $infoUser = $this->member_model->get_member($this->_user_id);
        $data = $this->_getData($infoUser, $_POST);
        $json = array();
        if ($this->form_validation->run() == true) {
            if($this->member_model->checkEmailAvaliable($data['lb_email'], $this->_user_id)) {
                $this->member_model->save_member($this->_user_id, $data);
                $json['status'] = true;
                $json['message'] ="Những thay đổi đã được lưu thành công";
            } else {
                $json['status'] = false;
                $json['message'] ="Email này đã được sử dụng bởi người khác";   
            }
        } else {
            $json['status'] = true;
            $json['message'] ="Không thể lưu những thay đổi";  
        }
        echo json_encode($json);
        exit();
    }
    
    private function _getData($data, $post) {
        $result = array();
        $result['lb_full_name'] = !empty($post['fullname'])?$post['fullname']:$data['lb_full_name'];
        $birthday = $data['lb_birthday'];
        $year = !empty($post['birth_date_year'])?$post['birth_date_year']:"";
        $month = !empty($post['birth_date_month'])?$post['birth_date_month']:"";
        $day = !empty($post['birth_date_day'])?$post['birth_date_month']:"";
        if(!empty($year) && !empty($month) && !empty($day) ) {
            $birthday = $year."-".$month."-".$day;
        }
        $result['lb_birthday'] = $birthday;
        $result['lb_address'] = !empty($post['address'])?$post['address']:$data['lb_address'];
        $result['lb_city'] = !empty($post['city'])?$post['city']:$data['lb_city'];
        $result['lb_state'] = !empty($post['state'])?$post['state']:$data['lb_state'];
        $result['lb_ward'] = !empty($post['ward'])?$post['ward']:$data['lb_ward'];
        $result['lb_phone'] = !empty($post['phone'])?$post['phone']:$data['lb_phone'];
        $result['lb_email'] = !empty($post['email'])?$post['email']:$data['lb_email'];
        if(!empty($post['password']) && !empty($post['password_confirm']) && $post['password'] == $post['password_confirm'] ) {
            $result['lb_password'] = md5($post['password']);
        }
        return $result;
    }
    public function get_state() {
        $cityId = $this->input->post("city_id");
        $this->load->helper('registration');
        $json = array();
        $json['status'] = true;
        $json['data'] = buildStateDropdown('state', '', $cityId);
        echo json_encode($json);
        exit();
    }

    function success() {
        $this->data['message'] = "<h1>User created successfully...</h1>";
        $this->load->view('register/success', $this->data);
    }

}